<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
  <title>批量必修课程</title>
  <!-- 引入jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  <style>
    .back-btn {
      display: block;
      text-align: center;
      margin-top: 25px;
    }

    .back-btn a {
      display: inline-block;
      padding: 10px 20px;
      background: linear-gradient(135deg, #95a5a6, #7f8c8d);
      color: white;
      border-radius: 5px;
      text-decoration: none;
      transition: all 0.3s ease;
    }

    .back-btn a:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
      text-decoration: none;
      color: white;
    }
    :root {
      --primary-color: #667eea;
      --secondary-color:  #764ba2;
      --accent-color: #e74c3c;
      --light-color: #ecf0f1;
      --success-color: #27ae60;
    }

    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      padding: 20px;
      min-height: 100vh;
    }

    .system-header {
      text-align: center;
      margin-bottom: 30px;
      color: var(--secondary-color);
    }

    .system-header h2 {
      font-weight: 700;
      font-size: 2rem;
      margin-bottom: 5px;
      background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .content-container {
      background: white;
      border-radius: 15px;
      padding: 30px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }

    .filter-form {
      background: #f8f9fa;
      border-radius: 10px;
      padding: 20px;
      margin-bottom: 25px;
    }

    .form-group {
      margin-bottom: 15px;
    }

    .form-label {
      font-weight: 600;
      color: var(--secondary-color);
      margin-bottom: 8px;
    }

    .form-select {
      border: 2px solid #e9ecef;
      border-radius: 8px;
      padding: 10px 15px;
      transition: all 0.3s ease;
    }

    .form-select:focus {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
    }

    .btn-primary {
      background: linear-gradient(175deg, #667eea, #764ba2);
      border: none;
      border-radius: 8px;
      padding: 10px 25px;
      font-weight: 600;
      transition: all 0.3s ease;
    }

    .btn-primary:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
    }

    .message-container {
      margin-bottom: 20px;
    }

    .error-message {
      background: linear-gradient(135deg, #e74c3c, #c0392b);
      color: white;
      padding: 15px 20px;
      border-radius: 8px;
      margin-bottom: 15px;
      font-weight: 600;
    }

    .success-message {
      background: linear-gradient(135deg, var(--success-color), #229954);
      color: white;
      padding: 15px 20px;
      border-radius: 8px;
      margin-bottom: 15px;
      font-weight: 600;
    }

    .table-container {
      background: white;
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    }

    .table {
      margin-bottom: 0;
    }

    .table thead th {
      background: linear-gradient(135deg, #302b63, #24243e);
      color: white;
      border: none;
      padding: 15px 20px;
      font-weight: 600;
    }

    .table tbody td {
      padding: 15px 20px;
      border-color: #e9ecef;
      vertical-align: middle;
    }

    .table tbody tr:hover {
      background-color: rgba(52, 152, 219, 0.05);
    }

    .assign-btn, .cancel-btn {
      padding: 8px 16px;
      border: none;
      border-radius: 6px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      font-size: 0.9rem;
    }

    .assign-btn {
      background: linear-gradient(135deg, var(--success-color), #229954);
      color: white;
    }

    .assign-btn:hover:not(:disabled) {
      transform: translateY(-2px);
      box-shadow: 0 3px 10px rgba(39, 174, 96, 0.3);
    }

    .cancel-btn {
      background: linear-gradient(135deg, #e74c3c, #c0392b);
      color: white;
    }

    .cancel-btn:hover:not(:disabled) {
      transform: translateY(-2px);
      box-shadow: 0 3px 10px rgba(231, 76, 60, 0.3);
    }

    .assign-btn:disabled, .cancel-btn:disabled {
      background: #95a5a6;
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }

    .status-text {
      margin-left: 10px;
      font-weight: 600;
      font-size: 0.9rem;
    }

    .status-assigned {
      color: var(--success-color);
    }

    .status-unassigned {
      color: #7f8c8d;
    }

    .action-container {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .content-container {
        padding: 20px;
      }

      .filter-form {
        padding: 15px;
      }

      .table thead th,
      .table tbody td {
        padding: 10px 15px;
      }
    }
  </style>
</head>
<body>
<div class="container">
  <div class="system-header">
    <h2>批量必修课程</h2>
  </div>

  <div class="content-container">
    <!-- 显示错误信息 -->
    <c:if test="${not empty errorMessage}">
      <div class="error-message">
        <i class="fas fa-exclamation-circle"></i> ${errorMessage}
      </div>
    </c:if>

    <!-- 显示成功信息 -->
    <c:if test="${not empty successMessage}">
      <div class="success-message">
        <i class="fas fa-check-circle"></i> ${successMessage}
      </div>
    </c:if>

    <!-- 添加筛选表单 -->
    <div class="filter-form">
      <form action="batchRequiredCourse" method="post" class="row g-3 align-items-end">
        <div class="col-md-4">
          <label for="majorId" class="form-label">专业</label>
          <select name="majorId" id="majorId" class="form-select">
            <option value="">请选择专业</option>
            <c:forEach items="${majors}" var="major">
              <option value="${major.id}" ${param.majorId == major.id ? 'selected' : ''}>
                  ${major.name}
              </option>
            </c:forEach>
          </select>
        </div>
        <div class="col-md-4">
          <label for="yearId" class="form-label">届数</label>
          <select name="yearId" id="yearId" class="form-select">
            <option value="">请选择届数</option>
            <c:forEach items="${years}" var="year">
              <option value="${year.id}" ${param.yearId == year.id ? 'selected' : ''}>
                  ${year.name}
              </option>
            </c:forEach>
          </select>
        </div>
        <div class="col-md-4">
          <button type="submit" class="btn btn-primary w-100">
            <i class="fas fa-filter"></i> 筛选
          </button>
        </div>
      </form>
    </div>

    <!-- 显示筛选结果 -->
    <div class="table-container">
      <table class="table table-hover">
        <thead>
        <tr>
          <th>课程编号</th>
          <th>课程名称</th>
          <th>学分</th>
          <th>专业</th>
          <th>届数</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <c:forEach items="${courses}" var="course">
          <tr>
            <td>${course.no}</td>
            <td>${course.name}</td>
            <td>${course.credit}</td>
            <td>${course.majorName}</td>
            <td>${course.yearName}</td>
            <td>
              <div class="action-container">
                                        <span class="assign-status" data-course-id="${course.no}">
                                            <button class="assign-btn">
                                                <i class="fas fa-tasks"></i> 分配课程
                                            </button>
                                            <span class="status-text"></span>
                                        </span>
              </div>
            </td>
          </tr>
        </c:forEach>
        </tbody>
      </table>
    </div>
  </div>
</div>
<div class="back-btn">
  <a href="javascript:history.back()"><i class="fas fa-arrow-left"></i> 返回</a>
</div>
<script>
  $(document).ready(function() {
    // 页面加载后检查所有课程的分配状态
    $('.assign-status').each(function() {
      var container = $(this);
      var courseId = container.data('course-id');
      var assignBtn = container.find('.assign-btn');
      var statusText = container.find('.status-text');
      checkAssignStatus(courseId, assignBtn, statusText);
    });

    // 检查分配状态的函数
    function checkAssignStatus(courseId, assignBtn, statusText) {
      $.ajax({
        url: '${pageContext.request.contextPath}/checkAssignStatus',
        type: 'GET',
        data: { courseId: courseId },
        dataType: 'json',
        success: function(data) {
          if (data.assigned) {
            // 已分配，显示取消分配按钮
            updateToAssignedState(assignBtn, statusText, courseId);
          } else {
            // 未分配，显示分配按钮
            updateToUnassignedState(assignBtn, statusText, courseId);
          }
        },
        error: function(xhr, status, error) {
          console.error('检查状态失败:', error);
          statusText.text('状态检查失败').addClass('status-unassigned');
        }
      });
    }

    // 更新为已分配状态
    function updateToAssignedState(assignBtn, statusText, courseId) {
      assignBtn.hide();
      statusText.html('<i class="fas fa-check-circle"></i> 已分配').removeClass('status-unassigned').addClass('status-assigned');

      // 移除已存在的取消按钮，避免重复添加
      statusText.next('.cancel-btn').remove();
      var cancelBtn = $('<button class="cancel-btn"><i class="fas fa-times-circle"></i> 取消分配</button>');

      cancelBtn.click(function() {
        cancelAssign(courseId, assignBtn, statusText, cancelBtn);
      });
      statusText.after(cancelBtn);
    }

    // 更新为未分配状态
    function updateToUnassignedState(assignBtn, statusText, courseId) {
      // 移除已存在的取消按钮
      statusText.next('.cancel-btn').remove();
      assignBtn.show().html('<i class="fas fa-tasks"></i> 分配课程').prop('disabled', false);
      assignBtn.off('click').on('click', function() {
        assignCourse(courseId, assignBtn, statusText);
      });
      statusText.text('').removeClass('status-assigned status-unassigned');
    }

    // 分配课程的函数
    function assignCourse(courseId, assignBtn, statusText) {
      assignBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 分配中...');

      $.ajax({
        url: '${pageContext.request.contextPath}/assignCourse',
        type: 'POST',
        data: { courseId: courseId },
        dataType: 'json',
        success: function(data) {
          console.log("分配响应:", data);
          if (data.success) {
            updateToAssignedState(assignBtn, statusText, courseId);
            alert(data.message);
          } else {
            alert('分配失败: ' + data.message);
            updateToUnassignedState(assignBtn, statusText, courseId);
          }
        },
        error: function(xhr, status, error) {
          console.error("AJAX错误:", xhr.status, error);
          alert('分配请求失败，请检查: ' + (xhr.status === 404 ? 'Servlet路径错误' : '网络连接'));
          updateToUnassignedState(assignBtn, statusText, courseId);
        }
      });
    }

    // 取消分配的函数
    function cancelAssign(courseId, assignBtn, statusText, cancelBtn) {
      if (confirm('确定要取消该课程的分配吗？')) {
        cancelBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 取消中...');

        $.ajax({
          url: '${pageContext.request.contextPath}/cancelAssign',
          type: 'POST',
          data: { courseId: courseId },
          dataType: 'json',
          success: function(data) {
            if (data.success) {
              updateToUnassignedState(assignBtn, statusText, courseId);
            } else {
              alert('取消分配失败: ' + (data.message || '未知错误'));
              cancelBtn.prop('disabled', false).html('<i class="fas fa-times-circle"></i> 取消分配');
            }
          },
          error: function() {
            alert('取消分配请求失败，请检查网络连接');
            cancelBtn.prop('disabled', false).html('<i class="fas fa-times-circle"></i> 取消分配');
          }
        });
      }
    }
  });
</script>
</body>
</html>